package com.neu.yth.nepBackend.grid.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neu.yth.nepBackend.entity.Grid;
import com.neu.yth.nepBackend.grid.mapper.GridMapper;
import com.neu.yth.nepBackend.grid.service.IGridService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neu.yth.nepBackend.utils.Result;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 区域网格信息 服务实现类
 * </p>
 *
 * @author YTH
 * @since 2024-06-12
 */
@Service
public class GridServiceImpl extends ServiceImpl<GridMapper, Grid> implements IGridService {

    /**
     * 获取所有区域网格信息
     *
     * @return
     */
    @Cacheable(value="nep-grids",key="'nep-grids'")
    @Override
    public Result<Grid> selectAllGridTree() {
        LambdaQueryWrapper<Grid> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        int pid = 0;
        lambdaQueryWrapper.eq( Grid::getPid , pid   );
        Grid root =  getBaseMapper().selectOne(  lambdaQueryWrapper );
        fillChildren(root);
        return Result.success(root);
    }

    private void fillChildren(Grid root) {

        int pid = root.getId();
        LambdaQueryWrapper<Grid> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Grid::getPid, pid);
        root.setChildren(getBaseMapper().selectList(lambdaQueryWrapper));

        if (root.getLevel() >= 3 || root.getChildren() == null || root.getChildren().size() == 0) {
            return;
        }
        if (root.getLevel() < 3) {
            root.getChildren().forEach((grid) -> {
                fillChildren(grid);
            });
        }
    }
}
